import java.util.Stack;

public class Leetcode235 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val < p.val && root.val < q.val) {
            return lowestCommonAncestor(root.right, p, q);
        }

        if (root.val > p.val && root.val > q.val) {
            return lowestCommonAncestor(root.left, p, q);
        }

        return root;
    }

    class Solution {
        public TreeNode dfs(TreeNode root, TreeNode p, TreeNode q) {
            if (root == p || root == q) {
                return root;
            }

            if ((p.val > root.val && q.val < root.val) || (q.val > root.val && p.val < root.val)) {
                return root;
            }

            if (p.val > root.val && q.val > root.val) {
                return dfs(root.right, p, q);
            }

            return dfs(root.left, p, q);
        }

        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            return dfs(root, p, q);
        }
    }
}
